<template>

    <div class="yc" :class="'imageWrapper' + index" v-for="(item, index) in allDataUrl" :key="index">
        <div class="content-imageWrapper">
            <div class="imageWrapper-box">
                <div class="title-box ">{{ item.name }}</div>
                <div class="imag-img mt5">
                    <img style="width: 100%;" :src="item.url"alt="">
                </div>
                <div class="title-box">{{ item.imei }}</div>
                <div class="title-box">{{ item.location }}</div>
                <div class="title-box">微信扫一扫</div>

            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import * as JSZip from 'jszip';
import FileSaver from 'file-saver';
import html2canvas from 'html2canvas';

// 响应式数据
const dialogInfoStyle = ref({ loading: false });
const allDataUrl = ref([]);
const finalCanvas = ref([]);
const title = ref('');

// 单张下载
const saveImage = (params) => {
    const imageWrapper = document.querySelector(`.imageWrapper0`);
    html2canvas(imageWrapper, { backgroundColor: "#fff" }).then((canvas) => {
        const imageURL = canvas.toDataURL("image/png");
        const link = document.createElement("a");
        link.href = imageURL;
        link.download = "页面截图.png";
        link.click();
    });
};

//获取数据
const getData = (data)=>{
  allDataUrl.value = data;
}


// 获取数据
const examScoreResultList = async (params) => {
    dialogInfoStyle.value.loading = true;
    try {

        await downloads(allDataUrl.value); // 等待下载完成
    } catch (error) {
        console.error('获取数据失败:', error);
    } finally {
        dialogInfoStyle.value.loading = false;
    }
};


// 下载图片并生成压缩包
const downloads = async (data) => {
    try {
        finalCanvas.value = [];
        const promises = data.map((item, index) => {
            console.log(item);

            return new Promise((resolve) => {
                const imageWrapper = document.querySelector(`.imageWrapper${index}`);
                html2canvas(imageWrapper, {
                    backgroundColor: "#fff"
                }).then((canvas) => {
                    console.log(canvas);
                    console.log(item);

                    finalCanvas.value.push({
                        fileUrl: canvas.toDataURL('image/png'),
                        renameFileName: `${item.name}${item.imei}.png`,
                    });
                    resolve();
                });
            });
        });

        await Promise.all(promises); // 等待所有图片转换完成
        await filesToRar(finalCanvas.value, '我的压缩包'); // 生成压缩包
    } catch (error) {
        ElMessage.error('下载失败');
        console.error('下载错误:', error);
    } finally {
        dialogInfoStyle.value.loading = false;
    }
};

// 生成压缩包
const filesToRar = async (arrImages, filename) => {
    try {
        title.value = '正在加载压缩文件';
        const zip = new JSZip();
        const promises = arrImages.map(async (item) => {
            const data = await getImgArrayBuffer(item.fileUrl);            
            zip.file(item.renameFileName, data, { binary: true });
        });

        await Promise.all(promises);        
        const content = await zip.generateAsync({ type: 'blob' });
        title.value = '压缩完成';
        FileSaver.saveAs(content, filename);
    } catch (error) {
        title.value = '压缩失败';
        ElMessage.error('文件压缩失败');
        throw error;
    }
};

// 获取图片的 ArrayBuffer（用于 JSZip）
const getImgArrayBuffer = (base64) => {
       return new Promise((resolve, reject) => {
        try {
            // 分离数据头和实际数据
            const parts = base64.split(',');
            if (parts.length < 2) {
                throw new Error('Invalid Base64 format');
            }
            
            // 解码Base64
            const byteString = atob(parts[1]);
            
            // 创建ArrayBuffer
            const arrayBuffer = new ArrayBuffer(byteString.length);
            const uintArray = new Uint8Array(arrayBuffer);
            
            for (let i = 0; i < byteString.length; i++) {
                uintArray[i] = byteString.charCodeAt(i);
            }
            
            resolve(arrayBuffer);
        } catch (error) {
            console.error('Base64转换失败:', error);
            reject(error);
        }
    });
};

// 暴露方法给模板（如果需要）
defineExpose({
    examScoreResultList,
    saveImage,
    getData
});
</script>
<style scoped lang="less">
.yc {
     position: fixed;
    z-index: -999;  
}
.content-imageWrapper {
    width: 1231px;
    height: 490px;
    background: #FFFFFF;


    background-image: url("@/assets/images/bz.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;

    box-sizing: border-box;
    padding: 66px 50px;
    


    

    .imageWrapper-box {
        width: 300px;
        height: 100%;

        display: flex;
        align-items: center;
        flex-direction: column;

        .title-box {
            font-weight: 500;
            font-size: 18px;
            color: #1A1A1A;
        }

        .imag-img {
            width: 260px;
            height: 260px;
            background-color: palegoldenrod;

        }
    }

    .mt5 {
        margin-top: 8px;
    }





   
}
</style>